package api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/model"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

var SysPermission = SysPermissionApi{}

type SysPermissionApi struct {
}

// Index 首页请求列表
func (s *SysPermissionApi) Index(r *ghttp.Request) {
	var searchParams *model.SysPermisssionGetListReq
	if err := r.ParseForm(&searchParams); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	permList, err := service.SysPermission.GetPermList(searchParams)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	var permTreeList []*model.SysPermissionTree
	if searchParams.Name == "" && searchParams.DisplayName == "" {
		permTreeOriginList := ([]model.SysPermissionTree)(nil)
		gconv.Structs(permList, &permTreeOriginList)
		permTreeList = service.SysPermission.BuildTree(permTreeOriginList)
	} else {
		gconv.Structs(permList, &permTreeList)
	}
	response.Json(r, 0, "加载成功", g.Map{
		"permList": permTreeList,
	})
}

// Save 保存权限数据
func (s *SysPermissionApi) Save(r *ghttp.Request) {
	var permData *model.SysPermissionSaveReq
	if err := r.ParseForm(&permData); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rs, err := service.SysPermission.SavePerm(permData)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rows, err := rs.RowsAffected()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "保存成功", g.Map{
		"rows": rows,
	})
}

// Destroy 删除权限
func (s *SysPermissionApi) Destroy(r *ghttp.Request) {
	var permIds []uint
	recPermIds := r.Get("perm_ids")
	permIds = gconv.SliceUint(recPermIds)
	rs, err := service.SysPermission.DelPerm(permIds)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rows, err := rs.RowsAffected()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "删除成功", g.Map{
		"rows": rows,
	})
}
